package com.ihisomp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ihisomp.base.Page;
import com.ihisomp.base.Result;
import com.ihisomp.dto.SysUserDto;
import com.ihisomp.entity.*;
import com.ihisomp.mapper.SysUserMapper;
import com.ihisomp.service.*;
import com.ihisomp.util.ComUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author zy
 * @since 2022-04-15
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private ISysGetNoService sysGetNoService;

    @Autowired
    private IOrgUserRoleService orgUserRoleService;

    @Autowired
    private IOrgUserDeptService orgUserDeptService;

    @Autowired
    private ISysUserWorkService sysUserWorkService;

    @Autowired
    private ISysUserOrgService sysUserOrgService;

    @Autowired
    private ISysUserParmService sysUserParmService;

    /**
     * 分页查询
     *
     * @param page
     * @param size
     * @param sysUserDto
     * @return
     */
    @Override
    public Result search(long page, long size, SysUserDto sysUserDto) {
        if (sysUserDto == null) {
            sysUserDto = new SysUserDto();
        }
        // 分页查询
        IPage<SysUser> data = baseMapper.searchPage(new Page<SysUser>(page, size), sysUserDto);
        return Result.ok(data);
    }

    /**
     * 新增用户
     *
     * @param sysUserDto
     * @return
     */
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED)
    @Override
    public Result add(SysUserDto sysUserDto) {
        // 判断用户名及密码不能为空
        if (StringUtils.isBlank(sysUserDto.getLoginName())) {
            return Result.error("用户账号不能为空！");
        }
        if (StringUtils.isBlank(sysUserDto.getPassword())) {
            return Result.error("用户密码不能为空！");
        }
        if (StringUtils.isBlank(sysUserDto.getDefaultDeptKey())) {
            return Result.error("用户默认科室不能为空！");
        }
        // 判断用户角色不能为空
        if (sysUserDto.getRoles() == null || sysUserDto.getRoles().size() <= 0) {
            return Result.error("用户角色不能为空！");
        }
        // 查询用户名是否存在
        if (getByLoginName(sysUserDto.getLoginName()) != null) {
            return Result.error("该用户账号已经存在！");
        }
        // 新增用户信息
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserDto, sysUser);
        String userKey = sysGetNoService.getSysNo("t_sys_user");
        sysUser.setUserKey(userKey);
        // 密码加密
        sysUser.setPassword(new BCryptPasswordEncoder().encode(sysUserDto.getPassword()));
        // 身份证号加密
        sysUser.setIdNumber(ComUtil.encryptDbField(sysUserDto.getIdNumber()));
        // 电话号码加密
        sysUser.setPhoneNumber(ComUtil.encryptDbField(sysUserDto.getPhoneNumber()));
        sysUser.setErrorCount(0);
        sysUser.setLoginNum(0);
        sysUser.setLoginNumToday(0);
        sysUser.setActiveFlg(1);
        if (baseMapper.insert(sysUser) > 0) {
            // 新增用户与机构关系
            SysUserOrg sysUserOrg = new SysUserOrg();
            sysUserOrg.setUserOrgKey(ComUtil.createPrimaryKey());
            sysUserOrg.setUserKey(userKey);
            sysUserOrg.setOrgKey(sysUserDto.getOrgKey());
            sysUserOrg.setMainFlg(1);
            if (!sysUserOrgService.save(sysUserOrg)) {
                return Result.error("新增用户与机构关系失败！");
            }
            // 新增用户个人参数
            SysUserParm sysUserParm = new SysUserParm();
            sysUserParm.setUserParmKey(ComUtil.createPrimaryKey());
            sysUserParm.setUserKey(userKey);
            sysUserParm.setOrgKey(sysUserDto.getOrgKey());
            if (!sysUserParmService.save(sysUserParm)) {
                return Result.error("新增用户个人参数失败！");
            }
            // 新增用户角色
            OrgUserRole orgUserRole = new OrgUserRole();
            orgUserRole.setUserKey(userKey);
            orgUserRole.setOrgKey(sysUserDto.getOrgKey());
            for (int i = 0; i < sysUserDto.getRoles().size(); i++) {
                orgUserRole.setUserRoleKey(ComUtil.createPrimaryKey());
                orgUserRole.setRoleKey(sysUserDto.getRoles().get(i));
                if (!orgUserRoleService.save(orgUserRole)) {
                    return Result.error("新增用户角色失败！");
                }
            }
            // 新增用户科室
            OrgUserDept orgUserDept = new OrgUserDept();
            // 添加默认科室数据
            orgUserDept.setUserDeptKey(ComUtil.createPrimaryKey());
            orgUserDept.setUserKey(userKey);
            orgUserDept.setDeptKey(sysUserDto.getDefaultDeptKey());
            orgUserDept.setMainFlg(1);
            orgUserDept.setOrgKey(sysUserDto.getOrgKey());
            if (!orgUserDeptService.save(orgUserDept)) {
                return Result.error("新增用户科室失败！");
            }
            // 添加其他科室数据
            orgUserDept.setMainFlg(0);
            for (int i = 0; i < sysUserDto.getDepts().size(); i++) {
                // 过滤默认科室
                if (sysUserDto.getDefaultDeptKey().equals(sysUserDto.getDepts().get(i))) {
                    continue;
                }
                orgUserDept.setUserDeptKey(ComUtil.createPrimaryKey());
                orgUserDept.setDeptKey(sysUserDto.getDepts().get(i));
                orgUserDept.setOrgKey(sysUserDto.getOrgKey());
                if (!orgUserDeptService.save(orgUserDept)) {
                    return Result.error("新增用户科室失败！");
                }
            }
            // 新增用户工种
            SysUserWork sysUserWork = new SysUserWork();
            sysUserWork.setUserKey(userKey);
            sysUserWork.setOrgKey(sysUserDto.getOrgKey());
            for (int i = 0; i < sysUserDto.getWorks().size(); i++) {
                sysUserWork.setUserWorkKey(ComUtil.createPrimaryKey());
                sysUserWork.setTypeOfWork(sysUserDto.getWorks().get(i));
                if (!sysUserWorkService.save(sysUserWork)) {
                    return Result.error("新增用户工种失败！");
                }
            }
        } else {
            return Result.error("新增用户信息失败！");
        }
        return Result.ok();
    }

    /**
     * 更新用户
     *
     * @param userKey
     * @param sysUserDto
     * @return
     */
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED)
    @Override
    public Result update(String userKey, SysUserDto sysUserDto) {
        SysUser sysUser = baseMapper.selectById(userKey);
        if (sysUser == null) {
            return Result.error("未查询到用户信息！");
        }
        // 实体类赋值
        sysUser.setUserName(sysUserDto.getUserName());
        sysUser.setPy(sysUserDto.getPy());
        sysUser.setSexKey(sysUserDto.getSexKey());
        sysUser.setBirthday(sysUserDto.getBirthday());
        // 身份证号加密
        sysUser.setIdNumber(ComUtil.encryptDbField(sysUserDto.getIdNumber()));
        // 电话号码加密
        sysUser.setPhoneNumber(ComUtil.encryptDbField(sysUserDto.getPhoneNumber()));
        sysUser.setNation(sysUserDto.getNation());
        sysUser.setEducation(sysUserDto.getEducation());
        sysUser.setIntroduction(sysUserDto.getIntroduction());
        sysUser.setTitleKey(sysUserDto.getTitleKey());
        sysUser.setPositionKey(sysUserDto.getPositionKey());
        sysUser.setDefaultDeptKey(sysUserDto.getDefaultDeptKey());
        sysUser.seteMail(sysUserDto.geteMail());
        sysUser.setDoctorServiceNo(sysUserDto.getDoctorServiceNo());
        sysUser.setDoctorCertificateNo(sysUserDto.getDoctorCertificateNo());
        sysUser.setAvatar(sysUserDto.getAvatar());
        sysUser.setUserPic(sysUserDto.getUserPic());
        sysUser.setPositionKey(sysUserDto.getPositionKey());
        if (baseMapper.updateById(sysUser) > 0) {
            // 1、更新用户角色
            OrgUserRole orgUserRole = new OrgUserRole();
            orgUserRole.setUserKey(userKey);
            orgUserRole.setOrgKey(sysUserDto.getOrgKey());
            // 1.1、删除用户角色
            if (orgUserRoleService.deleteByUserKey(userKey) < 0) {
                return Result.error("删除用户角色失败！");
            }
            // 1.2、新增用户角色
            for (int i = 0; i < sysUserDto.getRoles().size(); i++) {
                orgUserRole.setUserRoleKey(ComUtil.createPrimaryKey());
                orgUserRole.setRoleKey(sysUserDto.getRoles().get(i));
                if (!orgUserRoleService.save(orgUserRole)) {
                    return Result.error("新增用户角色失败！");
                }
            }
            // 2、更新用户科室
            OrgUserDept orgUserDept = new OrgUserDept();
            orgUserDept.setUserDeptKey(ComUtil.createPrimaryKey());
            orgUserDept.setUserKey(userKey);
            orgUserDept.setDeptKey(sysUserDto.getDefaultDeptKey());
            orgUserDept.setMainFlg(1);
            orgUserDept.setOrgKey(sysUserDto.getOrgKey());
            // 2.1、删除用户科室
            if (orgUserDeptService.deleteByUserKey(userKey) < 0) {
                return Result.error("删除用户角色失败！");
            }
            // 2.2、新增默认科室数据
            if (!orgUserDeptService.save(orgUserDept)) {
                return Result.error("新增用户科室失败！");
            }
            // 2.3、新增其他科室数据
            orgUserDept.setMainFlg(0);
            for (int i = 0; i < sysUserDto.getDepts().size(); i++) {
                // 过滤默认科室
                if (sysUserDto.getDefaultDeptKey().equals(sysUserDto.getDepts().get(i))) {
                    continue;
                }
                orgUserDept.setUserDeptKey(ComUtil.createPrimaryKey());
                orgUserDept.setDeptKey(sysUserDto.getDepts().get(i));
                orgUserDept.setOrgKey(sysUserDto.getOrgKey());
                if (!orgUserDeptService.save(orgUserDept)) {
                    return Result.error("新增用户科室失败！");
                }
            }
            // 3、更新用户工种
            SysUserWork sysUserWork = new SysUserWork();
            sysUserWork.setUserKey(userKey);
            sysUserWork.setOrgKey(sysUserDto.getOrgKey());
            // 3.1、删除用户工种
            if (sysUserWorkService.deleteByUserKey(userKey) < 0) {
                return Result.error("删除用户工种失败！");
            }
            // 3.2、新增用户工种
            for (int i = 0; i < sysUserDto.getWorks().size(); i++) {
                sysUserWork.setUserWorkKey(ComUtil.createPrimaryKey());
                sysUserWork.setTypeOfWork(sysUserDto.getWorks().get(i));
                if (!sysUserWorkService.save(sysUserWork)) {
                    return Result.error("新增用户工种失败！");
                }
            }
            return Result.ok();
        } else {
            return Result.error("更新用户信息失败！");
        }
    }

    /**
     * 查询用户
     *
     * @param userKey
     * @return
     */
    @Override
    public Result get(String userKey) {
        SysUserDto sysUserDto = new SysUserDto();
        BeanUtils.copyProperties(baseMapper.selectById(userKey), sysUserDto);
        // 身份证号解密
        sysUserDto.setIdNumber(ComUtil.decryptDbField(sysUserDto.getIdNumber()));
        // 电话号码解密
        sysUserDto.setPhoneNumber(ComUtil.decryptDbField(sysUserDto.getPhoneNumber()));
        // 用户角色
        sysUserDto.setRoles(orgUserRoleService.getRoleByUserKey(userKey));
        // 用户工种
        sysUserDto.setWorks(sysUserWorkService.getWorkByUserKey(userKey));
        // 用户其他科室
        sysUserDto.setDepts(orgUserDeptService.getOtherDeptByUserKey(userKey));
        return Result.ok(sysUserDto);
    }

    /**
     * 更新用户状态
     *
     * @param userKey
     * @param activeFlg
     * @return
     */
    @Override
    public Result updateStatus(String userKey, int activeFlg) {
        SysUser sysUser = baseMapper.selectById(userKey);
        if (sysUser == null) {
            return Result.error("无查询用户信息");
        }
        if (activeFlg == 0) {
            sysUser.setActiveFlg(1);
        } else {
            sysUser.setActiveFlg(0);
        }
        if (baseMapper.updateById(sysUser) > 0) {
            return Result.ok();
        }
        return Result.error("更新用户状态失败！");
    }

    /**
     * 修改用户密码
     *
     * @param sysUserDto
     * @return
     */
    @Override
    public Result updatePwd(SysUserDto sysUserDto) {
        if (sysUserDto == null || StringUtils.isEmpty(sysUserDto.getPassword())) {
            return Result.error("新密码不能为空！");
        }
        SysUser sysUser = baseMapper.selectById(sysUserDto.getUserKey());
        sysUser.setPassword(new BCryptPasswordEncoder().encode(sysUserDto.getPassword()));
        int i = baseMapper.updateById(sysUser);
        if (i < 1) {
            return Result.error("密码修改失败！");
        }
        return Result.ok();
    }

    /**
     * 查询门户用户名是否存在
     *
     * @param loginName
     * @return
     */
    private SysUser getByLoginName(String loginName) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name", loginName);
        return baseMapper.selectOne(queryWrapper);
    }

}
